# -*- coding: UTF-8 -*-

import xeres

from functor import *
from ui import image

#
#	Process property from ui-def file, translate specific property to style.
#

class CastFunc(object):

	# Property casting functions
	@staticmethod
	def default_cast( instance, value, package ):
		return value
	
	# Value casting
	
	# Casting to boolean value
	@staticmethod
	def to_bool( instance, value, package ):
		return bool(value)
	
	# Casting to integer value
	@staticmethod
	def to_int( instance, value, package ):
		return int(value)
	
	# Casting to float value
	@staticmethod
	def to_float( instance, value, package ):
		return float(value)
	
	# Casting to integer tuple
	@staticmethod
	def to_tuple_int( instance, value, package ):
		lst = value.split(',')
		for i in xrange(len(lst)):
			lst[i] = int(lst[i])
		return tuple(lst)
	
	# Casting to float tuple
	@staticmethod
	def to_tuple_float( instance, value, package ):
		lst = value.split(',')
		for i in xrange(len(lst)):
			lst[i] = float(lst[i])
		return tuple(lst)
	
	# Casting to string
	@staticmethod
	def to_str( instance, value, package ):
		return value
	
	# Cast to an event
	@staticmethod
	def to_event( instance, value, package ):
		return package.make_event( instance, value )
	
	# Cast to an image
	@staticmethod
	def to_image( instance, value, package ):
		pos = value.find(':')
		if pos == -1:
			return xeres.LoadImage('value')
		else:
			loader = value[:pos]
			img = value[pos+1:]
			iloader = image.get_loader(loader)
			if iloader:
				return iloader(img)
			return None
			
	# Cast to background, may have edge
	@staticmethod
	def to_background( instance, value, package ):
		params = value.split(',')
		l = len(params)
		#print "to_background" ,l,params
		if l == 1:
			return ( CastFunc.to_image( instance, value, package ), )

		img = CastFunc.to_image( instance, params[0], package )
		if img == None:
			return None

		if l == 2:
			edge = int(params[1])
			return (img,edge,edge)
		elif l == 3:
			return (img,int(params[1]),int(params[2]))
		else:
			raise ValueError, "Background parameter type mismatch."

#
# Registered properties.
__properties = {}

# Basic property
__properties['position'] 	= CastFunc.to_tuple_int
__properties['size'] 		= CastFunc.to_tuple_int
__properties['visible'] 	= CastFunc.to_bool
__properties['edge_size']	= CastFunc.to_tuple_int
__properties['edge']		= CastFunc.to_tuple_int

# Resource property
__properties['image'] 		= CastFunc.to_image
__properties['background'] 	= CastFunc.to_background

# Events
__properties['on_key'] 		= CastFunc.to_event
__properties['on_click'] 	= CastFunc.to_event
__properties['on_close'] 	= CastFunc.to_event


# Cast property to value
def cast_property( instance, name, value, package ):
	global __properties
	return __properties.get( name, CastFunc.default_cast )( instance, value, package )

